package book.zone.controller;

import book.zone.model.SignInModel;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: neveragny
 * Date: 19.05.2010
 * Time: 0:15:36
 */
public class SignInServlet extends HttpServlet {
    HttpSession session;
    SignInModel signinModel;

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        session = req.getSession();
        if(req.getParameter("action").equals("logout")){
            if(session != null){
                session.invalidate();
            }
        }
        resp.sendRedirect("/");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String passwd = req.getParameter("passwd");
        if(!(email.equals(null)) && !(passwd.equals(null))){
            signinModel = new SignInModel();
            session = req.getSession();
//            Logger.out("matchingCredentials " + signinModel.doMatch(email, passwd));
            if(signinModel.doMatch(email, passwd)){
                session.setAttribute("email", email);
            }
        }
        if (session.getAttribute("cart") == null){
            session.setAttribute("cart", new ArrayList());
        }
//        Logger.out("[SignIn]" +email + " " + passwd);
        resp.sendRedirect("/index.jsp");
    }
}
